package com.uex.dev.manage.common.base;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author wangc
 * @create 2023/10/8
 * @description
 */
@Schema(name = "分页查询返回参数")
@Data
public class PageResult<T> {
    @Schema(name = "当前页数据集")
    private List<T> dataList;
    @Schema(name = "总记录数")
    private Long total;

    public static <T> PageResult<T> build(Page<T> page) {
        PageResult<T> objectPageResult = new PageResult<>();
        objectPageResult.setTotal(page.getTotal());
        objectPageResult.setDataList(page.getRecords());

        return objectPageResult;
    }

    public <R> PageResult<R> convert(Function<T, R> convert) {
        PageResult<R> objectPageResult = new PageResult<>();
        objectPageResult.setTotal(this.getTotal());

        List<R> result = this.getDataList().stream().map(convert).collect(Collectors.toList());
        objectPageResult.setDataList(result);

        return objectPageResult;
    }

    public <R> PageResult<R> batchConvert(Function<List<T>, List<R>> convert) {
        PageResult<R> objectPageResult = new PageResult<>();
        objectPageResult.setTotal(this.getTotal());

        List<R> result = convert.apply(this.getDataList());
        objectPageResult.setDataList(result);

        return objectPageResult;
    }


    public static <T> PageResult<T> from(IPage<T> iPage) {
        PageResult<T> pageModel = new PageResult<>();
        pageModel.setDataList(iPage.getRecords());
        pageModel.setTotal(iPage.getTotal());

        return pageModel;
    }

    public static <T> PageResult<T> from(IPage iPage, List<T> records) {
        PageResult<T> pageModel = new PageResult<>();
        pageModel.setDataList(records);
        pageModel.setTotal(iPage.getTotal());

        return pageModel;
    }

    /**
     * 快速构造一个空的分页结果.
     *
     * @param pageArg 分页参数
     * @param <T> 分页的数据类型
     * @return 空的分页结果
     */
    public static <T> PageResult<T> emptyPage(PageArg pageArg) {
        PageResult<T> pageModel = new PageResult<>();
        return pageModel;
    }
}
